package com.bml.architect.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannel;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class AIOServer {

    public static void main(String[] args) throws IOException {

        final AsynchronousServerSocketChannel serverChannel = AsynchronousServerSocketChannel.open();

        serverChannel.bind(new InetSocketAddress(8000));

        serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
            @Override
            public void completed(AsynchronousSocketChannel socketChannel, Object attachment) {

                //再此接收客户端连接，如果不写这行代码后面的客户端连接连不上服务端
                serverChannel.accept(attachment, this);
                ByteBuffer buffer = ByteBuffer.allocate(1024);

                //异步读取数据
                socketChannel.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                    @Override
                    public void completed(Integer result, ByteBuffer attachment) {
                        buffer.flip();
                        System.out.println(new String(buffer.array(), 0, result));
                        socketChannel.write(ByteBuffer.wrap("HelloClient".getBytes()));
                    }

                    @Override
                    public void failed(Throwable exc, ByteBuffer attachment) {

                    }
                });

            }

            @Override
            public void failed(Throwable exc, Object attachment) {

            }
        });
        System.in.read();
    }
}
